<template>
  <aside class="sidebar" ref="sidebar" :class="[
    appStore.sidebarCollapsed ? 'collapsed' : '',
    appStore.mobileSidebarOpen ? 'open' : '',
  ]" @mouseleave="handleSidebarMouseLeave">
    <div class="brand">
      <div>
        <span v-if="appStore.sidebarCollapsed">
          <img src="@/assets/images/logo-icon.svg" alt="" class="logo-icon" />
        </span>
        <span v-else>
          <img src="@/assets/images/logo.svg" alt="" class="logo" />
        </span>
      </div>
    </div>

    <div class="menu">
      <template v-for="(item, index) in menuData" :key="item.title">
        <!-- 分类标题 -->
        <div class="menu-category" v-if="item.category && !appStore.sidebarCollapsed">
          {{ item.title }}
        </div>

        <!-- 带子菜单的菜单项 -->
        <div v-else-if="item.children" class="menu-parent" :class="{
          'has-children': true,
          'active-parent': isActiveParent(item),
          open: openedMenuIndex === index,
          'icon-hover':
            currentHoveredMenu === index && appStore.sidebarCollapsed,
        }" @click="toggleSubMenu(index)" @mouseenter="handleMenuMouseEnter(index, $event)">
          <div class="menu-item">
            <i :class="'iconfont ' + item.icon"></i>
            <span v-if="!appStore.sidebarCollapsed">{{ item.title }}</span>
            <span v-if="item.badge && !appStore.sidebarCollapsed" class="badge">{{ item.badge }}</span>
            <i v-if="item.children && !appStore.sidebarCollapsed" :class="[
              'iconfont right',
              openedMenuIndex === index
                ? 'icon-arrow-down'
                : 'icon-arrow-right',
            ]"></i>
          </div>

          <!-- 展开状态下的子菜单 -->
          <transition name="expand" @enter="enterTransition" @after-enter="afterEnterTransition" @leave="leaveTransition">
            <div class="submenu" v-if="openedMenuIndex === index && !appStore.sidebarCollapsed" ref="submenu">
              <router-link v-for="child in item.children" :key="child.path" :to="child.path" class="submenu-item"
                active-class="active">
                {{ child.title }}
                <span v-if="child.badge" class="badge">
                  {{ child.badge }}
                </span>
              </router-link>
            </div>
          </transition>
        </div>

        <!-- 普通菜单项 -->
        <router-link v-else-if="!item.category" :to="item.path" class="menu-item" active-class="active">
          <i :class="'iconfont ' + item.icon"></i>
          <span v-if="!appStore.sidebarCollapsed">{{ item.title }}</span>
          <span v-if="item.badge && !appStore.sidebarCollapsed" class="badge">{{
            item.badge
          }}</span>
        </router-link>
      </template>
    </div>

    <!-- 折叠状态下的悬浮子菜单 -->
    <div v-if="appStore.sidebarCollapsed && currentHoveredMenu !== null" class="floating-submenu"
      :style="floatingMenuStyle" @mouseenter="handleFloatingMenuEnter" @mouseleave="handleFloatingMenuLeave">
      <div class="floating-submenu-header">
        {{ menuData[currentHoveredMenu].title }}
      </div>
      <div class="submenu">
        <router-link v-for="child in menuData[currentHoveredMenu].children" :key="child.path" :to="child.path"
          class="submenu-item" active-class="active">
          {{ child.title }}
          <span v-if="child.badge" class="badge">{{ child.badge }}</span>
        </router-link>
      </div>
    </div>

    <!-- 移动端遮罩层 -->
    <div class="sidebar-overlay" v-if="appStore.mobileSidebarOpen" @click="appStore.toggleMobileSidebar"></div>
  </aside>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { useAppStore } from "@/stores/app";
import { getPermission, getUserInfo } from "@/utils/auth";

// 调试信息：打印当前用户权限
const userInfo = getUserInfo();
console.log('当前用户信息:', userInfo);

// 先获取用户权限
const userPermission = getPermission();
console.log('当前用户权限:', userPermission);
console.log('是否是超级管理员:', userPermission === 'superAdmin');

// 过渡动画组件
const enterTransition = (el) => {
  el.style.height = "0";
  el.offsetHeight; // 触发重排
  el.style.height = `${el.scrollHeight}px`;
};

const afterEnterTransition = (el) => {
  el.style.height = "auto";
};

const leaveTransition = (el) => {
  el.style.height = `${el.scrollHeight}px`;
  el.offsetHeight; // 触发重排
  el.style.height = "0";
};

const route = useRoute();
const appStore = useAppStore();
const sidebar = ref(null);
const openedMenuIndex = ref(null);
const currentHoveredMenu = ref(null);
const menuPosition = ref({ top: 0, left: 0 });

// 基础菜单数据
const baseMenuData = [
  { category: true, title: "USER MANAGEMENT" },
  // 为了测试，先不进行权限检查，直接添加用户管理菜单
  {
    title: "用户管理",
    icon: "icon-users",
    path: "/user",
  },

  {
    title: "公司管理",
    icon: "icon-hotel",
    path: "/company",
  },
  // {
  //   title: "职位管理",
  //   icon: "icon-themes",
  //   path: "/position",
  // },
  { category: true, title: "SETTING" },
  {
    title: "APP设置",
    icon: "icon-setting",
    path: "/setting/app",
  },
];

// 根据用户权限动态生成菜单
const menuData = computed(() => {
  // 只有超级管理员才能看到管理员管理菜单
  if (userPermission === 'superadmin') {
    // 在用户管理前面插入管理员管理菜单
    const menuCopy = [...baseMenuData];
    const userManagementIndex = menuCopy.findIndex(item => item.category && item.title === "USER MANAGEMENT");
    if (userManagementIndex !== -1) {
      menuCopy.splice(userManagementIndex + 1, 0, {
        title: "管理员管理",
        icon: "icon-user",
        path: "/admin",
      });
    }
    return menuCopy;
  }
  return baseMenuData;
});
const floatingMenuStyle = computed(() => ({
  top: `${menuPosition.value.top}px`,
  left: `${sidebar.value ? sidebar.value.clientWidth : 70}px`,
  backgroundColor: "var(--v-sidebar-background)",
}));

const isActiveParent = (parent) => {
  if (!parent.children) return false;
  return parent.children.some((child) => {
    return route.path.startsWith(child.path.split("/")[1]);
  });
};

const toggleSubMenu = (index) => {
  if (appStore.sidebarCollapsed) return;

  if (openedMenuIndex.value === index) {
    openedMenuIndex.value = null;
  } else {
    openedMenuIndex.value = index;
  }
};

const handleMenuMouseEnter = (index, event) => {
  if (!appStore.sidebarCollapsed) return;

  const menuItem = event.currentTarget;
  const rect = menuItem.getBoundingClientRect();

  menuPosition.value = {
    top: rect.top,
    left: rect.left,
  };

  currentHoveredMenu.value = index;
};

const handleFloatingMenuEnter = () => {
  // 保持悬浮菜单可见
};

const handleFloatingMenuLeave = () => {
  currentHoveredMenu.value = null;
};

const handleSidebarMouseLeave = () => {
  if (appStore.sidebarCollapsed) {
    currentHoveredMenu.value = null;
  }
};

// 点击外部关闭悬浮菜单
const handleClickOutside = (event) => {
  if (!sidebar.value) return;
  if (!sidebar.value.contains(event.target)) {
    currentHoveredMenu.value = null;
  }
};

onMounted(() => {
  document.addEventListener("click", handleClickOutside);
});

onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
});
</script>

<style lang="less" scoped>
.sidebar {
  width: var(--v-side-width);
  background: var(--v-sidebar-background);
  color: #a0aede;
  height: 100vh;
  position: relative;
  overflow-y: auto;
  transition: all 0.3s ease;
  z-index: 99;
}

.sidebar.collapsed {
  width: 70px;
}

.brand {
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  font-size: 20px;
  font-weight: bold;
  color: #fff;

  .logo {
    width: 90px;
    cursor: pointer;
  }

  .logo-icon {
    width: 28px;
    cursor: pointer;
  }
}

.menu-category {
  padding: 15px 20px 5px;
  font-size: 10px;
  font-weight: bold;
  color: #838fb9;
}

.menu-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 15px;
  color: #abb9e8;
  text-decoration: none;
  position: relative;

  .iconfont.right {
    font-size: 10px;
  }
}

.menu-parent {
  cursor: pointer;

  .menu-item {
    padding-right: 12px;
  }
}

.menu-item:hover,
.menu-parent:hover .menu-item {
  color: #fff;
}

.menu-item.active,
.menu-parent.active-parent .menu-item {
  color: #fff;
}

.menu-item i {
  font-size: 18px;
  transition: font-size 0.3s;
  transform-origin: center;
}

.badge {
  background-color: #ff9f43;
  color: white;
  border-radius: var(--v-card-radius);
  padding: 2px 10px;
  font-size: 12px;
  margin-left: auto;
}

/* 子菜单样式 */
.submenu {
  padding: 5px 0;
  margin-left: 25px;
  z-index: 9;
  position: relative;
}

.submenu-item {
  display: block;
  padding: 8px 20px 8px 35px;
  margin: 2px 0;
  border-radius: 6px;
  color: #abb9e8;
  font-size: 14px;
  text-decoration: none;
  transition: all 0.2s ease;
  position: relative;
  display: flex;
  align-items: center;

  &:hover {
    color: #fff;
  }

  &.active {
    color: #fff;
    background: rgba(255, 255, 255, 0.1);
  }

  .badge {
    margin-left: auto;
    margin-right: 5px;
  }
}

/* 折叠状态下的悬浮菜单 */
.floating-submenu {
  position: fixed;
  border-radius: 4px;
  overflow: hidden;
  z-index: 9;
  width: 200px;

  .floating-submenu-header {
    padding: 12px 20px;
    font-weight: bold;
    color: #fff;
    border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  }

  .submenu {
    border-left: none;
    margin-left: 0;
    padding: 5px 0;
  }

  .submenu-item {
    padding-left: 20px;
  }
}

/* 展开/收缩动画 */
.expand-enter-active,
.expand-leave-active {
  transition: height 0.3s ease;
  overflow: hidden;
}

.sidebar.collapsed {
  .menu-item i {
    font-size: 20px;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
    position: fixed;
    transition: transform 0.3s ease;
    width: var(--v-side-width) !important;
    z-index: 1000;
  }

  .sidebar.open {
    transform: translateX(0);
  }

  .sidebar.collapsed {
    width: var(--v-side-width) !important;

    .menu-item i {
      font-size: 22px;
    }
  }

  .sidebar-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 999;
    display: none;
  }

  .sidebar.open+.sidebar-overlay {
    display: block;
  }

  /* 在移动端隐藏悬浮菜单 */
  .floating-submenu {
    display: none;
  }
}

.expand-enter-active,
.expand-leave-active {
  transition: height 0.3s ease;
  overflow: hidden;
}
</style>